<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-form :model="queryParams" inline>
      <el-form-item label="场馆名称">
        <el-input v-model="queryParams.stadiumName" placeholder="请输入场馆名称" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作栏 -->
    <div class="mb-4">
      <el-button type="primary" v-hasPermi="['sys:ad:btn_add']" @click="handleAdd"
        >新增广告</el-button
      >
    </div>

    <!-- 数据表格 -->
    <el-table :data="list" v-loading="loading">
      <el-table-column prop="stadiumName" label="场馆名称" />
      <el-table-column prop="type" label="广告类型">
        <template #default="{ row }">
          <el-tag :type="row.type === 1 ? 'primary' : 'success'">
            {{ typeFormat(row.type) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="url" label="资源">
        <template #default="{ row }">
          <el-image
            v-if="row.url != null && row.url != ''"
            style="
              max-width: 100px;
              max-height: 60px;
              cursor: pointer;
              display: flex;
              align-items: center;
            "
            :src="row.url"
            fit="contain"
            :preview-src-list="[row.url]"
            :z-index="9999"
          >
            <template #error>
              <div class="image-error">
                <i class="el-icon-picture-outline" />
              </div>
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="160" />
      <el-table-column prop="updateTime" label="更新时间" width="160" />
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button type="primary" link v-hasPermi="['sys:ad:btn_update']" @click="handleEdit(row)"
            >编辑</el-button
          >
          <el-button
            type="primary"
            link
            v-hasPermi="['sys:ad:btn_remove']"
            @click="handleDelete(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <Pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="500px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="form" label-width="100px">
        <el-form-item>
          <el-upload
            :action="actionUrl"
            :limit="1"
            :headers="myHeaders"
            :file-list="fileList"
            :on-success="handleUploadSuccess"
            :on-remove="handleFileRemove"
            :on-change="handleFileChange"
            list-type="picture-card"
            accept="image/*"
            :before-upload="beforeUpload"
            :class="{ hideUpload: hideUploadBtn }"
          >
            <i class="el-icon-plus" />
          </el-upload>
        </el-form-item>

        <el-form-item label="场馆名称" prop="stadiumName">
          <el-select
            v-model="form.stadiumName"
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词"
            :remote-method="searchStadium"
            :loading="stadiumLoading"
            @change="handleStadiumChange"
          >
            <el-option
              v-for="item in stadiumOptions"
              :key="item.id"
              :label="item.stadiumName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="广告类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型">
            <el-option label="轮播图" :value="0" />
            <el-option label="活动图" :value="1" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="open = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElForm, ElMessage, ElMessageBox } from 'element-plus'
import { quickSearchStadium } from '@/api/site/site'
import { listAd, updateAd, createAd, deleteAd } from '@/api/ad/ad'
import * as imageConversion from 'image-conversion'
import Pagination from '@/components/Pagination/index.vue'
import env from '@/utils/env'

interface QueryParams {
  pageNum: number
  pageSize: number
  keyWord: string
  stadiumName: string | null
}

interface AdItem {
  id: string | null
  stadiumId: string | null
  stadiumName: string | null
  type: number | null
  url: string | null
  createTime?: string
  updateTime?: string
}

interface StadiumOption {
  id: string
  stadiumName: string
}

const myHeaders = { token: 'u05801#123' }

const queryParams = reactive<QueryParams>({
  pageNum: 1,
  pageSize: 10,
  keyWord: '',
  stadiumName: null,
})

const list = ref<AdItem[]>([])
const total = ref(0)
const loading = ref(false)
const open = ref(false)
const title = ref('')
const stadiumLoading = ref(false)
const stadiumOptions = ref<StadiumOption[]>([])
const form = reactive<AdItem>({
  id: null,
  stadiumId: null,
  stadiumName: null,
  type: null,
  url: null,
})
const fileList = ref<any[]>([])
const actionUrl = env.VITE_APP_BASE_API + '/file/qiniu/upload/img'
const hideUploadBtn = ref(false)

const formRef = ref<InstanceType<typeof ElForm>>()

// 计算是否隐藏上传按钮
const isUploadButtonHidden = computed(() => {
  console.log(fileList.value)
  return fileList.value.length >= 1
})

// 获取数据列表
const getList = () => {
  loading.value = true
  listAd(queryParams).then((response) => {
    list.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 重置查询条件
const resetQuery = () => {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    stadiumName: null,
  })
  getList()
}

// 搜索
const handleSearch = () => {
  queryParams.pageNum = 1
  getList()
}

// 格式化广告类型
const typeFormat = (type: number | null) => {
  if (type === 0) {
    return '轮播图'
  } else if (type === 1) {
    return '活动图'
  } else {
    return '未知'
  }
}

// 新增
const handleAdd = () => {
  Object.assign(form, {
    id: null,
    stadiumId: null,
    stadiumName: null,
    type: null,
    url: null,
  })
  title.value = '新增广告'
  open.value = true
}

// 编辑
const handleEdit = (row: AdItem) => {
  Object.assign(form, row)
  console.log(row)
  title.value = '修改'
  if (row.url != null && row.url != '') {
    fileList.value = [
      {
        url: row.url,
      },
    ]
  }
  hideUploadBtn.value = fileList.value.length >= 1
  open.value = true
}

// 删除
const handleDelete = async (row: AdItem) => {
  try {
    await ElMessageBox.confirm('确认删除该广告？', '提示', { type: 'warning' })
    await deleteAd(row.id as string)
    ElMessage.success('删除成功')
    getList()
  } catch {
    ElMessage.info('操作已取消')
  }
}

// 表单提交
const submitForm = async () => {
  if (!formRef.value) return

  await formRef.value.validate()
  if (form.id) {
    await updateAd(form)
  } else {
    await createAd(form)
  }
  ElMessage.success('操作成功')
  open.value = false
  getList()
}

const handleUploadSuccess = (response: any) => {
  form.url = response.msg // 根据实际接口响应结构调整
}

// 上传图片
const handleFileChange = () => {
  console.log(hideUploadBtn.value)
  hideUploadBtn.value = fileList.value.length >= 1
}

const handleFileRemove = () => {
  form.url = null
  console.log(fileList.value)
  hideUploadBtn.value = fileList.value.length >= 1
}

// 上传图片之前压缩图片
const beforeUpload: Fn = (file: File) => {
  return new Promise((resolve) => {
    imageConversion.compress(file, 1).then((res) => {
      const compressedFile = new File([res], file.name, {
        type: res.type,
        lastModified: Date.now(),
      })
      resolve(compressedFile)
    })
  })
}

const searchStadium = async (query: string) => {
  if (query) {
    stadiumLoading.value = true
    try {
      const res = await quickSearchStadium({ keyword: query })
      stadiumOptions.value = res.data || []
    } finally {
      stadiumLoading.value = false
    }
  } else {
    stadiumOptions.value = []
  }
}

// 选中框值改变时触发
const handleStadiumChange = (selectedId: string) => {
  console.log(selectedId)
  form.stadiumId = selectedId
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
:deep(.el-upload-list--picture-card .el-upload-list__item-thumbnail) {
  object-fit: cover;
}
:deep(.hideUpload .el-upload--picture-card) {
  display: none;
}
</style>
